package com.hare.auth.utils;


import cn.hutool.core.util.ObjectUtil;

import com.hare.common.exception.ServiceException;
import com.hare.common.global.constant.BaseConstant;
import com.hare.common.global.enums.ResultCode;
import com.hare.auth.base.BaseLoginUser;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @program: Hare
 * @description: 用户信息工具类
 * @author: Hare
 * @create: 2022-11-04 09:29
 * @Version 6.0.1
 **/
public class SecurityUtils {


    /**
     * 获取用户信息
     *
     * @return
     */
    public static BaseLoginUser getAdmin() {
        try {
            return (BaseLoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        } catch (Exception e) {
            throw new ServiceException(ResultCode.UNAUTHORIZED.getCode(), "获取用户信息异常");
        }
    }

    /**
     * 是否是超级管理员用户
     *
     * @param userId 用户id
     * @return
     */
    public static boolean isAdmin(String userId) {
        if (ObjectUtil.isNotNull(userId) && BaseConstant.ADMIN.equals(userId)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 是否是超级管理员角色
     *
     * @param roleId 角色id
     * @return
     */
    public static boolean isAdminRole(String roleId) {
        if (ObjectUtil.isNotNull(roleId) && BaseConstant.ADMIN_ROLE.equals(roleId)) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 生成BCryptPasswordEncoder密码
     *
     * @param password 密码
     * @return 加密字符串
     */
    public static String encryptPassword(String password) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.encode(password);
    }
}
